package com.yuwei.module_sign

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.bw.lib_base.path.RouterPath
import com.bw.lib_common.view.BaseMvvmActivity
import com.tencent.mmkv.MMKV
import com.yuwei.module_sign.databinding.ActivitySignBinding
import java.text.SimpleDateFormat
import java.util.*

@Route(path = RouterPath.MODULE_SIGN_ACTIVITY)
class SignActivity : BaseMvvmActivity<ActivitySignBinding>() {
    private lateinit var handler: Handler
    private lateinit var runnable: Runnable
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    var lat = 0
    var lon = 0
    //声明AMapLocationClientOption对象
    var mLocationOption: AMapLocationClientOption? = null
    //声明AMapLocationClient类对象
    var mLocationClient: AMapLocationClient? = null
    //声明定位回调监听器
    private val mLocationListener = AMapLocationListener { amapLocation ->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                //可在其中解析amapLocation获取相应内容。
                Log.i("local", ": 地址：${amapLocation.latitude},${amapLocation.longitude}}")
                lat = amapLocation.latitude.toInt()
                lon = amapLocation.longitude.toInt()
                val geocoderSearch = GeocodeSearch(this);
                geocoderSearch.setOnGeocodeSearchListener(object :
                    GeocodeSearch.OnGeocodeSearchListener {
                    override fun onRegeocodeSearched(p0: RegeocodeResult?, p1: Int) {
                        p0?.run {
                            val address = regeocodeAddress.formatAddress
                            Log.i("address", "onRegeocodeSearched: $address")
                            binding.signAddress.text = address
                        }
                    }

                    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {

                    }

                })

                // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系

                // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                val query = RegeocodeQuery(
                    LatLonPoint(amapLocation.latitude, amapLocation.longitude),
                    200f,
                    GeocodeSearch.AMAP
                )

                geocoderSearch.getFromLocationAsyn(query)
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e(
                    "AmapError", "location Error, ErrCode:"
                            + amapLocation.errorCode + ", errInfo:"
                            + amapLocation.errorInfo
                );
            }
        }
    }
    override fun initViews() {
        val currentTime = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        val formatterTime = SimpleDateFormat("yyyy-MM-dd")
        val formatterTimeClass = SimpleDateFormat("EEEE")
        binding.timeYear.text = ""+formatterTime.format(System.currentTimeMillis())+" "+formatterTimeClass.format(System.currentTimeMillis())
        handler = Handler()
        runnable = object :Runnable{
            override fun run() {
                val formatter1 = System.currentTimeMillis()
                val tt = currentTime.format(formatter1)
                binding.timeHour.text = ""+tt
                handler.postDelayed(this,1000)
            }
        }
        handler.post(runnable)
        binding.signBack.setOnClickListener {
            finish()
        }
        getLocal()
        updateButtonState()
        binding.tvClock.setOnClickListener{
            togglePunchState()
        }
    }
    override fun observeDataChange() {

    }

    override fun getLayoutId(): Int = R.layout.activity_sign
    private fun getLocal() {
        //初始化定位
        mLocationClient = AMapLocationClient(applicationContext)

        //设置定位回调监听
        mLocationClient!!.setLocationListener(mLocationListener)

        //初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()

        val option = AMapLocationClientOption()
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        option.locationPurpose = AMapLocationClientOption.AMapLocationPurpose.SignIn
        if (null != mLocationClient) {
            mLocationClient!!.setLocationOption(option)
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient!!.stopLocation()
            mLocationClient!!.startLocation()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(runnable)
        mLocationClient?.onDestroy()
        mLocationClient = null
    }
    private fun togglePunchState() {
        val lastPunchType = MMKV.defaultMMKV().getString(KEY_LAST_PUNCH_TYPE, null)
        val currentDate = getCurrentDate()

        if (lastPunchType == null || lastPunchType == PUNCH_OUT) {
            // 上班打卡
            val now = Date()
            MMKV.defaultMMKV().putString(KEY_LAST_PUNCH_TYPE, PUNCH_IN)
            MMKV.defaultMMKV().putString(KEY_LAST_PUNCH_IN_TIME, dateFormat.format(now))
            MMKV.defaultMMKV().putString(KEY_LAST_PUNCH_DATE, currentDate)
        } else {
            // 下班打卡
            val now = Date()
            MMKV.defaultMMKV().putString(KEY_LAST_PUNCH_TYPE, PUNCH_OUT)
            MMKV.defaultMMKV().putString(KEY_LAST_PUNCH_OUT_TIME, dateFormat.format(now))
        }

        updateButtonState()
    }

    private fun updateButtonState() {
        val lastPunchType = MMKV.defaultMMKV().getString(KEY_LAST_PUNCH_TYPE, null)
        val currentDate = getCurrentDate()
        val lastPunchDate = MMKV.defaultMMKV().getString(KEY_LAST_PUNCH_DATE, "")

        if (lastPunchType == null || currentDate != lastPunchDate) {
            binding.tvClock.isEnabled = true
            // 新的一天或从未打卡过
            binding.tvClock.text = "上班打卡"
            binding.signType.text = "上班打卡"
            binding.tvClock.setBackgroundResource(R.drawable.shape_clock_te_bg2)
        } else if (lastPunchType == PUNCH_IN) {
            // 已上班打卡，等待下班打卡
            binding.tvClock.text = "下班打卡"
            binding.signType.text = "下班打卡"
            binding.tvClock.setBackgroundResource(R.drawable.shape_clock_te_bg3)
        } else {
            // 已下班打卡
            binding.tvClock.text = "今日已完成打卡"
            binding.signType.text = "完成打卡"
            binding.tvClock.isEnabled = false
            binding.tvClock.setBackgroundResource(R.drawable.shape_clock_te_bg4)
        }
        binding.history.setOnClickListener {
            ARouter.getInstance().build(RouterPath.MODULE_SIGN_DETAIL_ACTIVITY).navigation()
        }
    }

    private fun getCurrentDate(): String {
        return SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
    }
    companion object {
        private const val KEY_LAST_PUNCH_TYPE = "last_punch_type"
        private const val KEY_LAST_PUNCH_IN_TIME = "last_punch_in_time"
        private const val KEY_LAST_PUNCH_OUT_TIME = "last_punch_out_time"
        private const val KEY_LAST_PUNCH_DATE = "last_punch_date"
        private const val PUNCH_IN = "punch_in"
        private const val PUNCH_OUT = "punch_out"
    }

}